
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_user_id
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import pandas as pd
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
# -*- coding: utf-8 -*-


class FriendsCircleMessageObject():
    '''老友圈对象'''

    def __init__(self, user_id, content, picture, location):
        '''构造函数'''
        # 操作人id
        self.user_id = user_id
        # 内容
        self.content = content
        # 图片
        self.picture = picture
        # 定位
        self.location = location

    def to_dict(self):
        return self.__dict__


class FriendsCircleCommentObject():
    '''老友圈评论对象'''

    def __init__(self, user_id, fcm_id, content):
        '''构造函数'''
        # 操作人id
        self.user_id = user_id
        # 信息id
        self.fcm_id = fcm_id
        # 内容
        self.content = content

    def to_dict(self):
        return self.__dict__


class FriendsCircleLikeObject():
    '''老友圈点赞对象'''

    def __init__(self, user_id, fcm_id, like):
        '''构造函数'''
        # 操作人id
        self.user_id = user_id
        # 信息id
        self.fcm_id = fcm_id
        # 点赞
        self.like = like

    def to_dict(self):
        return self.__dict__


"""
老友圈管理函数
"""


class FriendsCircleService(MongoService):
    """ 老友圈管理 """

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session
        )

    def get_friends_circle_list(self, condition, page, count):
        """获取老友圈广场列表

        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        """
        keys = ["id", "is_own", "user_id", "fcm_id"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        if 'is_own' in condition.keys():
            user_id = get_current_user_id(self.session)
            print('user_id>>', user_id)
            _filter.match_bill((C('user_id') == user_id))
        _filter.match_bill((C("id") == values["id"]) & (C("user_id") == values["user_id"]) & (C("fcm_id") == values["fcm_id"]))\
            .lookup_bill('PT_User', 'user_id', 'id', 'user')\
            .add_fields({
                "name": self.ao.array_elemat("$user.name", 0),
                "user_picture": self.ao.array_elemat("$user.personnel_info.picture_list", 0)
            })\
            .lookup_bill('PT_Friend_Circle_Comment', 'id', 'fcm_id', 'comment')\
            .lookup_bill('PT_Friend_Circle_Like', 'id', 'fcm_id', 'clike')\
            .project({"clike._id": 0})\
            .add_fields({'like_list': self.ao.array_filter("$clike", "aa", ((F('$aa.like') == True)).f)})\
            .sort({'create_date': -1})\
            .project({"_id": 0, "comment._id": 0,  "clike": 0, "user": 0})
        res = self.page_query(_filter, "PT_Friend_Circle_Message", page, count)
        return res

    def get_my_friends_circle_list(self, condition, page, count):
        ''' 获取好友老友圈列表 '''
        return []

    def update_friends_circle(self, content, picture, location):
        """ 发布老友圈 """
        res = 'Fail'
        data = FriendsCircleMessageObject(
            get_current_user_id(self.session), content, picture, location).to_dict()
        data_info = get_info(data, self.session)
        bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                    TypeId.friendsCircle.value, data_info, 'PT_Friend_Circle_Message')
        if bill_id:
            res = "Success"
        return res

    def delete_friends_circle(self, friends_circle_ids):
        '''删除老友圈接口
        Arguments:
            friends_circle_ids   {ids}      数据id
        '''
        res = 'Fail'
        ids = []
        if isinstance(friends_circle_ids, str):
            ids.append(friends_circle_ids)
        else:
            ids = friends_circle_ids
        for friends_circle_id in ids:
            self.bill_manage_service.add_bill(
                OperationType.delete.value, TypeId.friendsCircle.value, [{'id': friends_circle_id}], ['PT_Friend_Circle_Message'])
        res = 'Success'
        return res

    def update_commont(self, fcm_id, common):
        ''' 发布评论 '''
        user_id = get_current_user_id(self.session)
        data = FriendsCircleCommentObject(user_id, fcm_id, common).to_dict()
        data_info = get_info(data, self.session)
        bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                    TypeId.friendsCircle.value, data_info, 'PT_Friend_Circle_Comment')
        if bill_id:
            res = "Success"
        return res

    def del_commont(self, comment_ids):
        ''' 删除评论 '''
        res = 'Fail'
        ids = []
        if isinstance(comment_ids, str):
            ids.append(comment_ids)
        else:
            ids = comment_ids
        for comment_id in ids:
            self.bill_manage_service.add_bill(
                OperationType.delete.value, TypeId.friendsCircle.value, [{'id': comment_id}], ['PT_Friend_Circle_Comment'])
        res = 'Success'
        return res

    def update_like(self, fcm_id, like_type):
        ''' 点赞 type:0 取消点赞，1点赞'''
        res = "Fail"
        user_id = get_current_user_id(self.session)
        res_data = []

        def process_func(db):
            nonlocal res_data
            res_data = find_data(db, "PT_Friend_Circle_Like", {
                                 "fcm_id": fcm_id, "user_id": user_id, "bill_status": Status.bill_valid.value})
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        operation_type = OperationType.add.value
        data = {}
        if len(res_data) > 0:
            '''更新已有的'''
            data = res_data[0]
            operation_type = OperationType.update.value
            if like_type == 0:
                data['like'] = False
            else:
                data['like'] = True
        else:
            '''新增新的'''
            operation_type = OperationType.add.value
            data_info = {'user_id': user_id, 'fcm_id': fcm_id}
            data = get_info(data_info, self.session)
            if like_type == 0:
                data['like'] = False
            else:
                data['like'] = True
        bill_id = self.bill_manage_service.add_bill(operation_type,
                                                    TypeId.friendsCircle.value, data, 'PT_Friend_Circle_Like')
        if bill_id:
            res = "Success"
        return res

    def get_commont_list(self, condition, page, count):
        ''' 查询评论列表 '''
        keys = ["id", "is_own", "content"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C("id") == values["id"]))
        if 'is_own' in condition.keys():
            user_id = get_current_user_id(self.session)
            _filter.match_bill((C('user_id') == user_id))
        _filter.lookup_bill('PT_User', 'user_id', 'id', 'user')\
            .add_fields({
                "name": self.ao.array_elemat("$user.name", 0),
                "user_picture": self.ao.array_elemat("$user.personnel_info.picture_list", 0)
            })\
            .lookup_bill('PT_Friend_Circle_Message', 'fcm_id', 'id', 'circle')\
            .add_fields({'circle_object': self.ao.array_elemat("$circle", 0)})\
            .match_bill((C("circle_object.content").like(values["content"]) | C("content").like(values["content"]) | C("name").like(values["content"])))\
            .lookup_bill('PT_User', 'circle_object.user_id', 'id', 'circle_object_user')\
            .add_fields({'circle_user_name': self.ao.array_elemat("$circle_object_user.name", 0), 'circle_user_picture': self.ao.array_elemat("$circle_object_user.personnel_info.picture_list", 0), 'circle_content': '$circle_object.content'})\
            .sort({'create_date': -1})\
            .project({"_id": 0, "comment._id": 0,  "user": 0, "circle": 0, 'circle_object_user': 0, 'circle_object': 0})
        res = self.page_query(_filter, "PT_Friend_Circle_Comment", page, count)
        return res

    def get_like_list(self, condition, page, count):
        ''' 查询点赞列表 '''
        keys = ["id", "is_own", "content"]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('like') == True) & (C("id") == values["id"]))
        if 'is_own' in condition.keys():
            user_id = get_current_user_id(self.session)
            _filter.match_bill((C('user_id') == user_id))
        _filter.lookup_bill('PT_User', 'user_id', 'id', 'user')\
            .add_fields({
                "name": self.ao.array_elemat("$user.name", 0),
                "user_picture": self.ao.array_elemat("$user.personnel_info.picture_list", 0)
            })\
            .lookup_bill('PT_Friend_Circle_Message', 'fcm_id', 'id', 'circle')\
            .add_fields({'circle_object': self.ao.array_elemat("$circle", 0)})\
            .match_bill((C("circle_object.content").like(values["content"]) | C("name").like(values["content"])))\
            .lookup_bill('PT_User', 'circle_object.user_id', 'id', 'circle_object_user')\
            .add_fields({'circle_user_name': self.ao.array_elemat("$circle_object_user.name", 0), 'circle_user_picture': self.ao.array_elemat("$circle_object_user.personnel_info.picture_list", 0), 'circle_content': '$circle_object.content'})\
            .sort({'create_date': -1})\
            .project({"_id": 0, "comment._id": 0,  "user": 0, "circle": 0, 'circle_object_user': 0, 'circle_object': 0})
        res = self.page_query(_filter, "PT_Friend_Circle_Like", page, count)
        return res
